/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ias.springnote.db;

import com.springnote.api.PageType;
import ias.json2list.Transformer;
import ias.springnote.rest.ResourceException;
import ias.springnote.rest.RestClient;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author ias
 */
public class Database {

  private RestClient client;
  private Transformer transformer;
  private int root;

  Database(String userId, String userKey, String appKey, String domain) {
    client = new RestClient(userId, userKey, appKey);
    client.setDomain(domain);
    transformer = new Transformer();
  }

  public void deleteDocument(Document doc) throws ResourceException {
    client.deletePage(doc.getPage().getIdentifier());
  }

  public List<Document> getAllDocuments() {
    // TODO implement!
    return null;
  }

  public Document getDocument(int i) throws ResourceException, XMLStreamException, JSONException {
    PageType page = client.getPage(i);
    JSONObject object = transformer.convertList(page.getSource());
    object.put("id", i);
    object.put("created_at", page.getDateCreated().toString());
    object.put("updated_at", page.getDateModified().toString());
    return new Document(page, object);
  }

  public void saveDocument(Document document) throws XMLStreamException, JSONException, ResourceException {
    PageType page = document.getPage();
    JSONObject object = document.getObject();
    if (page == null) {
      // create
      page = new PageType();
      if (root != 0) {
        page.setRelationIsPartOf(root);
      }
      page.setTitle(String.valueOf(System.currentTimeMillis()));
      page.setSource(transformer.convertJson(object));
      page = client.createPage(page);
      object.put("id", page.getIdentifier());
      object.put("created_at", page.getDateCreated().toString());
      object.put("updated_at", page.getDateModified().toString());
    } else {
      // update
      object.remove("id");
      object.remove("created_at");
      object.remove("updated_at");
      page.setSource(transformer.convertJson(object));
      client.updatePage(page);
    }
  }

  public void setRoot(int root) {
    this.root = root;
  }

}
